<template>
  <div class="body">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-body">
        <div class="sidebar-header">
          CHAT
          <div>A.I +</div>
        </div>
        <ChatSidebar :conversations="conversations" @select-conversation="selectConversation" @new-chat="createNewChat" />
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="ChatContent">
      <ChatContent :messages="currentMessages" @send-message="sendMessage" />
    </div>

    <!-- 右侧升级提示 (中等屏幕以上显示) -->
    <!-- <div class="w-72 hidden lg:block p-6">
      <UpgradeCard />
    </div> -->
  </div>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue';
  import ChatSidebar from './components/ChatSidebar.vue';
  import ChatContent from './components/ChatContent.vue';
  // import UpgradeCard from './components/UpgradeCard.vue';
  import { Conversation, Message } from './types/chat';
  // 模拟对话数据
  // 表示一个「对话会话」的类型（包含对话 ID、标题、最后一条消息等信息）
  const conversations = ref<Conversation[]>([
    {
      id: '1',
      title: 'Create Chatbot GPT Environment Environment...',
      lastMessage: 'What is use of that chatbot ?',
      updatedAt: new Date(),
      isActive: true,
    },
    {
      id: '2',
      title: 'Create Html Game Environment Environment...',
      lastMessage: 'How to structure the game loop?',
      updatedAt: new Date(Date.now() - 86400000),
      isActive: false,
    },
    {
      id: '3',
      title: 'Apply To Leave For Emergency Environment',
      lastMessage: 'What documents are required?',
      updatedAt: new Date(Date.now() - 2 * 86400000),
      isActive: false,
    },
    {
      id: '4',
      title: 'What is UI UX Design Environment Environment?',
      lastMessage: 'Explain the difference between UI and UX',
      updatedAt: new Date(Date.now() - 3 * 86400000),
      isActive: false,
    },
    {
      id: '5',
      title: 'Create Html Game Environment Environment...',
      lastMessage: 'How to structure the game loop?',
      updatedAt: new Date(Date.now() - 86400000),
      isActive: false,
    },
    {
      id: '6',
      title: 'Apply To Leave For Emergency Environment',
      lastMessage: 'What documents are required?',
      updatedAt: new Date(Date.now() - 2 * 86400000),
      isActive: false,
    },
    {
      id: '7',
      title: 'What is UI UX Design Environment Environment?',
      lastMessage: 'Explain the difference between UI and UX',
      updatedAt: new Date(Date.now() - 3 * 86400000),
      isActive: false,
    },
  ]);

  // 模拟消息数据
  // 存储每个对话的消息列表
  const messages = ref<Record<string, Message[]>>({
    '1': [
      {
        id: '1-1',
        content: 'Create a chatbot gpt using python language what will be step for that',
        sender: 'user',
        timestamp: new Date(Date.now() - 3600000),
      },
      {
        id: '1-2',
        content: `Sure, I can help you get started with creating a chatbot using GPT in Python. Here are the basic steps you'll need to follow:

1. Install the required libraries: You'll need to install the transformers library from Hugging Face to use GPT. You can install it using pip.

2. Load the pre-trained model: GPT comes in several sizes and versions, so you'll need to choose the one that fits your needs. You can load a pre-trained GPT model. This loads the 1.3B parameter version of GPT-Neo, which is a powerful and relatively recent model.

3. Create a chatbot loop: You'll need to create a loop that takes user input, generates a response using the GPT model, and outputs it to the user. Here's an example loop that uses the input() function to get user input and the gpt() function to generate a response. This loop will keep running until the user exits the program or the loop is interrupted.

4. Add some personality to the chatbot: While GPT can generate text, it doesn't have any inherent personality or style. You can make your chatbot more interesting by adding custom prompts or responses that reflect your desired personality. You can then modify the chatbot loop to use these prompts when appropriate. This will make the chatbot seem more human-like and engaging.

These are just the basic steps to get started with a GPT chatbot in Python. Depending on your requirements, you may need to add more features or complexity to the chatbot. Good luck!`,
        sender: 'ai',
        timestamp: new Date(Date.now() - 3500000),
      },
      {
        id: '1-3',
        content: 'What is use of that chatbot ?',
        sender: 'user',
        timestamp: new Date(Date.now() - 3000000),
      },
      {
        id: '1-4',
        content: `Chatbots can be used for a wide range of purposes, including:

Customer service chatbots can handle frequently asked questions, provide basic support, and help customers`,
        sender: 'ai',
        timestamp: new Date(Date.now() - 2900000),
      },
    ],
  });

  const currentConversationId = ref('1'); //当前选中的对话 ID

  const currentMessages = computed(() => {
    return messages.value[currentConversationId.value] || [];
  });

  // 切换选中的对话
  const selectConversation = (id: string) => {
    // 更新所有对话的选中状态（只有当前ID的对话为激活状态）
    conversations.value = conversations.value.map((conv) => ({
      ...conv,
      isActive: conv.id === id,
    }));
    // 更新当前选中的对话ID
    currentConversationId.value = id;
  };

  // 创建新对话
  const createNewChat = () => {
    const newId = Date.now().toString();
    const newConversation: Conversation = {
      id: newId,
      title: 'New Chat',
      lastMessage: '',
      updatedAt: new Date(),
      isActive: true,
    };

    // 添加新对话并切换
    conversations.value = [newConversation, ...conversations.value.map((conv) => ({ ...conv, isActive: false }))];

    messages.value[newId] = [];
    currentConversationId.value = newId;
  };

  const sendMessage = (content: string) => {
    // 发送消息（用户消息 + 模拟 AI 回复）
    // 添加用户消息
    const newMessage: Message = {
      id: `${currentConversationId.value}-${Date.now()}`,
      content,
      sender: 'user',
      timestamp: new Date(),
    };

    if (!messages.value[currentConversationId.value]) {
      messages.value[currentConversationId.value] = [];
    }

    messages.value[currentConversationId.value].push(newMessage);

    // 更新对话列表中的最后一条消息
    conversations.value = conversations.value.map((conv) => {
      if (conv.id === currentConversationId.value) {
        return {
          ...conv,
          lastMessage: content,
          updatedAt: new Date(),
          title: conv.title === 'New Chat' ? content.substring(0, 30) : conv.title,
        };
      }
      return conv;
    });

    // 模拟AI回复
    setTimeout(() => {
      const aiResponse: Message = {
        id: `${currentConversationId.value}-${Date.now() + 1}`,
        content: 'Thank you for your message! This is an automated response from the AI chatbot.',
        sender: 'ai',
        timestamp: new Date(),
      };

      messages.value[currentConversationId.value].push(aiResponse);

      // 更新对话列表中的最后一条消息为AI回复
      conversations.value = conversations.value.map((conv) => {
        if (conv.id === currentConversationId.value) {
          return {
            ...conv,
            lastMessage: aiResponse.content.substring(0, 30),
            updatedAt: new Date(),
          };
        }
        return conv;
      });
    }, 1000);
  };
</script>

<style lang="scss" scoped>
  .body {
    display: flex;
    height: 100%;
    width: 100%;
    background-color: #fdfeff;
    .sidebar {
      height: 100%;
      width: 17%;
      display: flex;
      align-items: center;
      justify-content: center;
      .sidebar-body {
        height: 98%;
        width: 100%;
        background-color: #ffffff;
        box-shadow: 14px 17px 40px 4px rgba(112, 144, 176, 0.08);
        border-radius: 14px;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        .sidebar-header {
          width: 90%;
          height: 5%;
          display: flex;
          font-size: 3.3vh;
          font-weight: 500;
          text-shadow: 0 0 10px rgba(172, 172, 172, 0.5);
          color: #000;
          letter-spacing: 5px;
          padding-left: 5px;
          div {
            margin-left: 10px;
            height: 100%;
            font-weight: 500;
          }
        }
      }
    }
    .ChatContent {
      height: 100%;
      width: 83%;
    }
  }
</style>
